#!/usr/bin/env python

import requests
import argparse

class FileManager:
    def __init__(self,headers, api):
        self.api = api
        self.headers = headers

    def download(self, key):
        file_url = f"{self.api}/api/pipeline/artifact/download"
        params = {'md5': key}
        print(f"下载文件URL: {file_url},  params: {params}")
        try:
            response = requests.get(file_url, stream=True, params=params, headers=self.headers)
            response.raise_for_status()
            filename = response.headers.get('content-disposition').split('=')[-1]
            with open(filename, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
            return filename
        except Exception as e:
            print(f"下载文件URL: {file_url},  params: {params}, 下载失败: {e}")
            return None
    def get_laster_version(self, project):
        url = f"{self.api}/api/pipeline/artifact/project/{project}/latest/list"
        try:
            response = requests.get(url, headers=self.headers)
            response.raise_for_status()
            data = response.json()
            if data['code'] != 200:
                print(f"获取最新版本失败, 错误信息: {data['msg']}")
                return None
            return data['data']
        except Exception as e:
            print(f"获取最新版本失败: {e}")
            return None
    
    def verify_md5(self, md5, filepath):
        import hashlib
        with open(filepath, 'rb') as f:
            file_md5 = hashlib.md5()
            while chunk := f.read(8192):
                file_md5.update(chunk)
        return file_md5.hexdigest() == md5


    def upload_file(self, filename):
        upload_url = f"{self.api}/api/sys/files/upload"
        headers = self.headers.copy()
        # 移除手动设置的Content-Type，让requests库自动设置包含boundary的multipart/form-data头部
        if 'Content-Type' in headers:
            del headers['Content-Type']
        try:
            with open(filename, 'rb') as f:
                files = {'file': (filename, f)}
                response = requests.post(upload_url, headers=headers, files=files)
                response.raise_for_status()
                data = response.json()
                if data['code'] != 200:
                    print(f"上传文件失败, 错误信息: {data['msg']}")
                    return None
                return data['data']
        except Exception as e:
            print(f"上传文件失败: {e}")
            return None

def download_apps(token,project):
    headers = {'Authorization': f'{token}',
        'Host': 'devops.yocyl.com'
    }
    download = FileManager(headers, 'http://139.224.66.183')
    latest_apps = download.get_laster_version(project)
    if latest_apps:
        for app in latest_apps:
            print(f"最新版本: {app['version']}")
            filename = download.download(app['fileHash'])
            if filename:
                print(f"文件下载成功: {filename}")
                if download.verify_md5(app['fileHash'], filename):
                    print(f"文件MD5校验成功: {filename}")
                else:
                    print(f"文件MD5校验失败: {filename}")

def upload_file(token,filename):
    headers = {'Authorization': f'{token}',
        'Host': 'devops.yocyl.com'
    }
    upload = FileManager(headers, 'http://139.224.66.183')
    res = upload.upload_file(filename)
    if res:

        print(f"文件上传成功: https://devops.yocyl.com/api/sys/files/{res}")



def setup_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="优财运维管理工具",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    subparsers = parser.add_subparsers(dest='command', required=True)
    download_parser = subparsers.add_parser('download', help='下载应用文件')
    download_parser.add_argument('project',default='uat', help='项目名称')
    download_parser.add_argument('-t', '--token',default=token, help='认证token')
    file_parser = subparsers.add_parser('upload', help='上传文件')
    file_parser.add_argument('path', help='文件路径')
    file_parser.add_argument('-t', '--token',default=token, help='认证token')
    return parser


def main() -> None:
    parser = setup_parser()
    args = parser.parse_args()

    if args.command == 'download':
        download_apps(args.token, args.project)
    elif args.command == 'upload':
        upload_file(args.token, args.path)

if __name__ == '__main__':
    token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTg4OTQ5NjksImlkIjoxLCJ1c2VybmFtZSI6ImFkbWluIn0.Y3nrt0gIXV5kZPkc9s1LUx3UMoWApXFNP0kxs7YnrFc'
    project = 'uat'
    main()
    

    

